import {message} from 'antd';

export default class Chat {
  static channels: { [chanel: string]: (data: any) => any } = {};

  static interval: any = null;

  protected webSocket: WebSocket;

  constructor(token: string) {
    this.webSocket = new WebSocket(`ws://106.13.168.150:9502?token=${token}`);
  }

  onOpen = () => {
    message.info('webSocket已连接');
  };

  onMessage = (e: MessageEvent) => {
    const data = JSON.parse(e.data);
    console.log('onMessage');
    console.log(data);
    if (Chat.channels[data.channel]) {
      Chat.channels[data.channel](data.data);
    }
  };

  onClose = () => {
    message.info('已离开');
  };

  onError = () => {
    message.warn('webSocket onError');
    this.webSocket.close();
  };

  on = (channel: string, callback: (data: any) => void) => {
    Chat.channels[channel] = callback;
    return this;
  };

  start = () => {
    this.webSocket.onopen = this.onOpen;
    this.webSocket.onmessage = this.onMessage;
    this.webSocket.onclose = this.onClose;
    this.webSocket.onerror = this.onError;
    return this;
  };

  send = (data: string) => {
    this.webSocket.send(data);
  };

  close = () => {
    message.info('websocket close');
    if (Chat.interval) {
      clearInterval(Chat.interval);
    }
    this.webSocket.close();
  };

  heartbeat = (second: number = 3) => {
    Chat.interval = setInterval(() => {
      this.send('ping');
    }, second * 1000);
  };
}
